package com.yoke.assistant.remote;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.yoke.assistant.event.JsEvent;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import org.greenrobot.eventbus.EventBus;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * 本地UDP端口监听和数据接收类。
 *
 * @author jack.jiang＠52im.net, 2016-06-27
 * @version 1.0
 */
public class LocalUDPDataReciever {
    public static final int PORT = 5678;
    private static final String TAG = LocalUDPDataReciever.class.getSimpleName();
    private static LocalUDPDataReciever instance = null;
    private Thread thread = null;
    private Context context = null;
    private DatagramSocket localUDPSocket;
    private boolean running = true;

    public static LocalUDPDataReciever getInstance(Context context) {
        if (instance == null) {
            instance = new LocalUDPDataReciever(context);
        }
        return instance;
    }

    private LocalUDPDataReciever(Context context) {
        this.context = context;
    }

    public void startup() {
        this.thread = new Thread(new Runnable() {
            public void run() {
                try {
                    Log.d(LocalUDPDataReciever.TAG,
                            "本地UDP端口侦听中，端口=" + PORT + "...");
                    DatagramChannel channel= DatagramChannel.open();
                    channel.socket().bind(new InetSocketAddress(PORT));
                    localUDPSocket = channel.socket();
                    //开始侦听
                    LocalUDPDataReciever.this.udpListeningImpl();
                } catch (Exception eee) {
                    Log.w(LocalUDPDataReciever.TAG, "本地UDP监听停止了(socket被关闭了?)," + eee.getMessage(),
                            eee);
                }
            }
        });
        this.thread.start();
    }

    public void stop() {
        running = false;
        localUDPSocket.close();
    }

    private void udpListeningImpl() throws Exception {
        while (running) {
            byte[] data = new byte[4096];
            // 接收数据报的包
            DatagramPacket packet = new DatagramPacket(data, data.length);

            if ((localUDPSocket == null) || (localUDPSocket.isClosed())) {
                continue;
            }
            ByteBuffer buf = ByteBuffer.allocate(4096);
            buf.clear();
            // 阻塞直到收到数据
            InetSocketAddress receive = (InetSocketAddress) localUDPSocket.getChannel().receive(buf);
            buf.flip();
            // 解析服务端发过来的数据
            String receiveText = new String(buf.array(), "UTF-8");
            Log.w(LocalUDPDataReciever.TAG,"【NOTE】>>>>>> " + receiveText);
            try {
                UDPMessage udpMessage = JSON.parseObject(receiveText, UDPMessage.class);
                EventBus.getDefault().post(new JsEvent(udpMessage.getJs()));
            } catch (Exception e) {
                Logger.e("parse error", e);
            }
        }
    }
}